<template>
  <view class="my-page">
    <NavBar title="个人信息" />

    <view class="user-info">
      <view class="avatar">
        <Image :src="formData.avatarUrl" class="avatar-image" />
      </view>

      <text class="edit" @tap="handleToEdit">修改</text>
    </view>

    <view class="rows">
      <view class="row">
        <view class="row-item">
          <view class="required">*</view>
          <view class="label">姓名</view>
        </view>

        <view class="row-input">
          <input
            class="input"
            type="text"
            placeholder="请输入姓名"
            v-model="formData.nickName"
          />
        </view>
      </view>
    </view>

    <view class="footer">
      <view class="btn" @tap="handleSave">
        <text class="text">保存</text>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import NavBar from "../../components/NavBar.vue";
import Taro from "@tarojs/taro";
import { useReady } from "@tarojs/taro";
import { useUserStore } from "../../stores/userStore";
import { fileBase64Upload } from "../../api/common.api";
import { updateCmUser } from "../../api/user.api";
import { regExp } from "../../utils/valid.util";
import { safeNavigateBack } from "../../utils/navigation.util";
import { ref } from "vue";

const userState = useUserStore();
const formData = ref<{
  avatarUrl: string;
  nickName: string;
}>({
  avatarUrl: "",
  nickName: "",
});
const loading = ref(false);

// 修改图片
const handleToEdit = () => {
  // 选择图片
  Taro.chooseImage({
    count: 1, // 默认9
    sizeType: ["compressed"], // 可以指定是原图还是压缩图，默认二者都有
    sourceType: ["album", "camera"], // 可以指定来源是相册还是相机，默认二者都有，在H5浏览器端支持使用 `user` 和 `environment`分别指定为前后摄像头
    success: async function (res) {
      // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
      const tempFilePaths = res.tempFilePaths;

      // 转化为base64
      const base64 = Taro.getFileSystemManager().readFileSync(
        tempFilePaths[0],
        "base64"
      );

      // 拼接mime
      const mime = tempFilePaths[0].split(".")[1];

      // 拼接base64
      const base64Str = `data:image/${mime};base64,${base64}`;

      // 上传文件
      const response = await fileBase64Upload({ baseStr: base64Str });

      if (response.code === "200") {
        formData.value.avatarUrl = response.data || "";
      }
    },
  });
};

const getInfo = async () => {
  await userState.getCmUserByIdApi();

  formData.value.avatarUrl = userState.userInfo?.avatarUrl || "";
  formData.value.nickName = userState.userInfo?.nickName || "";
};

const handleSave = async () => {
  if (loading.value) return;

  try {
    loading.value = true;

    // 姓名不能为空
    if (!formData.value.nickName) {
      Taro.showToast({
        title: "请输入姓名",
        icon: "none",
      });
      return;
    } else {
      // 必须是中文
      if (!regExp.name.test(formData.value.nickName)) {
        Taro.showToast({
          title: "姓名必须是中文",
          icon: "none",
        });
        return;
      }
      // 长度不能超过10个字符
      if (formData.value.nickName.length > 15) {
        Taro.showToast({
          title: "姓名长度不能超过10个字符",
          icon: "none",
        });
        return;
      }
    }

    const res = await updateCmUser({
      nickName: formData.value.nickName,
      avatarUrl: formData.value.avatarUrl,
    });

    if (res.code === "200") {
      await getInfo();

      Taro.showToast({
        title: "保存成功",
        icon: "success",
      });

      safeNavigateBack();
    } else {
      Taro.showToast({
        title: res.msg,
        icon: "none",
      });
    }
  } catch (error) {
    console.log(error);
  } finally {
    loading.value = false;
  }
};

useReady(() => {
  if (!userState.userInfo) {
    getInfo();
  } else {
    formData.value.avatarUrl = userState.userInfo.avatarUrl || "";
    formData.value.nickName = userState.userInfo.nickName || "";
  }
});
</script>

<style lang="scss">
.my-page {
  display: flex;
  flex-direction: column;
  width: 100%;
  min-height: 100vh;
  background-color: white;

  .user-info {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding-top: 20px;
    padding-left: 16px;
    padding-right: 16px;

    .avatar {
      width: 85px;
      padding-bottom: 10px;

      .avatar-image {
        width: 85px;
        height: 85px;
        border-radius: 50%;
        overflow: hidden;
      }
    }

    .edit {
      font-weight: 400;
      font-size: 14px;
      color: #16ada4;
      font-style: normal;
    }

    .user-info-name {
      display: flex;
      align-items: center;
      // gap: 8px;
      gap: 4px;

      .user-info-name-text {
        font-weight: 500;
        font-size: 18px;
        color: #333333;
        text-align: left;
        font-style: normal;
        text-transform: none;
      }

      .user-info-name-icon {
        width: 22px;
        height: 22px;
      }
    }
  }

  .rows {
    width: 100%;
    padding: 0px 16px;

    .row {
      display: flex;
      align-items: center;
      justify-content: space-between;
      width: 100%;
      padding: 16px 0px;
      border-bottom: 1px solid #f5f6fa;

      .row-item {
        display: flex;
        align-items: center;
        gap: 2px;

        .required {
          font-weight: 400;
          font-size: 14px;
          color: #d90000;
          font-style: normal;
        }

        .label {
          font-weight: 400;
          font-size: 14px;
          color: #333333;
          text-align: left;
          font-style: normal;
          text-transform: none;
        }
      }

      .row-input {
        flex: 1;
        padding-left: 30px;

        .input {
          width: 100%;
          font-weight: 400;
          font-size: 14px;
          color: rgba(0, 0, 0, 0.9);
          text-align: right;
          font-style: normal;
        }
      }
    }
  }

  .footer {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
    margin-top: auto;
    padding: 30px 16px;

    .btn {
      display: flex;
      align-items: center;
      justify-content: center;
      gap: 5px;
      width: 100%;
      height: 45px;
      background: #16ada4;
      border-radius: 30px 30px 30px 30px;
      font-weight: 500;
      font-size: 16px;
      color: #ffffff;

      .icon {
        font-size: 20px;
      }
    }
  }
}
</style>
